package cn.edu.zstu.qingzhu.qingzhushop.controller;

import cn.edu.zstu.qingzhu.qingzhushop.entity.AuthenticationUser;
import cn.edu.zstu.qingzhu.qingzhushop.entity.ChatMessage;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Controller;

import java.util.Date;

/**
 * @Author ShenTuZhiGang
 * @Version 1.0.0
 * @Date 2020-04-12 13:23
 */
@Controller
@Api(tags = "WebSocket API接口")
public class WebSocketController {
    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    /**
     *
     * @param authentication
     * @param chatMsg
     */
    @MessageMapping("/ws/chat")
    public void handleMsg(Authentication authentication, ChatMessage chatMsg) {
        AuthenticationUser user = (AuthenticationUser) authentication.getPrincipal();
        chatMsg.setFrom(user.getUsername());
        chatMsg.setFromNickname(user.getNickname());
        chatMsg.setDate(new Date());
        simpMessagingTemplate.convertAndSendToUser(chatMsg.getTo(), "/queue/chat", chatMsg);
    }
}